package com.skywork.configuration;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;

@Configuration
public class WebMvcJsonConfig extends WebMvcConfigurerAdapter {

	@Value("${spring.mvc.prop.snake.case:true}")
	private String propName;

	@Value("${spring.mvc.prop.includ.empty:true}")
	private String inEmpty;
	
	@Autowired
	private ObjectFactory<HttpMessageConverters> messageConverters;

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		super.configureMessageConverters(converters);

		for (HttpMessageConverter<?> messageConverter : messageConverters.getObject().getConverters()) {
			if (messageConverter instanceof MappingJackson2HttpMessageConverter) {
				ObjectMapper objectMapper = ((MappingJackson2HttpMessageConverter) messageConverter).getObjectMapper();
				if (StringUtils.equals("true", inEmpty)) {
					objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
				}
				if (StringUtils.equals("true", propName)) {
					objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
				}
			}
		}

		// final MappingJackson2HttpMessageConverter converter = new
		// MappingJackson2HttpMessageConverter();
		// final ObjectMapper objectMapper = new ObjectMapper();
		// objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
		// objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
		// converter.setObjectMapper(objectMapper);
		// converters.add(converter);

	}

}
